package com.happy.ibidding.controller;

import com.happy.ibidding.service.FileService;
import com.happy.ibidding.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @GetMapping("/{fileId}")
    @ResponseBody
    public void getFile(@PathVariable String fileId, HttpServletResponse response) throws Exception {
        File file = fileService.getFile(fileId);
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStream fis = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();

        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileId, "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream");
        response.getOutputStream().write(buffer);
        response.getOutputStream().flush();
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        return this.fileService.saveFile(file.getBytes(), file.getOriginalFilename());
    }


}